package com.wewins.fota.sys.task;

import com.alibaba.fastjson.JSON;
import com.wewins.fota.bean.bo.ServerInfo;
import com.wewins.fota.bean.bo.UploadFile;
import com.wewins.fota.constant.FotaConst;
import com.wewins.fota.sys.config.FotaConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;

@Slf4j
@Component
public class ClearInvalidFileTask implements TimerTask {
    private final RedisTemplate<String, String> template;

    private final ServerInfo serverInfo;

    public ClearInvalidFileTask(RedisTemplate<String, String> template, ServerInfo serverInfo) {
        this.template = template;
        this.serverInfo = serverInfo;
    }

    @Override
    public void execute() {
        HashMap<String, UploadFile> rst = new HashMap<>();
        template.opsForHash().entries(FotaConst.REDIS_KEY_INVALID_FILE).forEach((key, value) -> {
            UploadFile uploadFile = JSON.parseObject((String) value, UploadFile.class);
            if (needClear(uploadFile)) {
                rst.put((String) key, uploadFile);
            }
        });
        rst.forEach((key, item) -> {
            File file = new File(item.getPath());
            boolean exists = file.exists();
            boolean ok = clear(file);
            if (exists && !ok) {
                log.info("failed to delete invalid file, wait next period. file:" + item.getPath());
                return;
            }
            template.opsForHash().delete(FotaConst.REDIS_KEY_INVALID_FILE, key);
            log.info("invalid file delete success, exist:" + exists + ", delete:" + ok + ", file:" + item.getPath());
        });
    }

    private boolean clear(File file) {
        boolean ok = file.delete();
        File parentFile = file.getParentFile();
        String[] children = parentFile.list();
        if (children != null && children.length == 0) {
            return ok && clear(parentFile);
        }
        return ok;
    }

    private boolean needClear(UploadFile uploadFile) {
        return serverInfo.getKey().equals(uploadFile.getServerKey()) &&
                System.currentTimeMillis() > uploadFile.getUploadTime();
    }
}
